<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"><title>Kotlin编程第一课--(协程篇)20  Flow：为什么说Flow是“冷”的？ | 码行</title><meta name="author" content="Carl Su"><meta name="copyright" content="Carl Su"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="ffffff"><meta name="description" content="今天我们来学习 Kotlin 协程 Flow 的基础知识。 Flow，可以说是在 Kotlin 协程当中自成体系的知识点。Flow 极其强大、极其灵活，在它出现之前，业界还有很多质疑 Kotlin 协程的声音，认为 Kotlin 的挂起函数、结构化并发，并不足以形成核心竞争力，在异步、并发任务的领域，RxJava 可以做得更好。 但是，随着 2019 年 Kotlin 推出 Flow 以后，这样的">
<meta property="og:type" content="article">
<meta property="og:title" content="Kotlin编程第一课--(协程篇)20  Flow：为什么说Flow是“冷”的？">
<meta property="og:url" content="https://devsu.top/posts/e7c23ba1/index.html">
<meta property="og:site_name" content="码行">
<meta property="og:description" content="今天我们来学习 Kotlin 协程 Flow 的基础知识。 Flow，可以说是在 Kotlin 协程当中自成体系的知识点。Flow 极其强大、极其灵活，在它出现之前，业界还有很多质疑 Kotlin 协程的声音，认为 Kotlin 的挂起函数、结构化并发，并不足以形成核心竞争力，在异步、并发任务的领域，RxJava 可以做得更好。 但是，随着 2019 年 Kotlin 推出 Flow 以后，这样的">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://img1.baidu.com/it/u=4050062314,1116360005&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500">
<meta property="article:published_time" content="2022-05-30T01:51:38.000Z">
<meta property="article:modified_time" content="2023-03-27T02:56:47.917Z">
<meta property="article:author" content="Carl Su">
<meta property="article:tag" content="Kotlin">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://img1.baidu.com/it/u=4050062314,1116360005&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500"><link rel="shortcut icon" href="https://s2.loli.net/2023/03/09/whMHdYkrKoIBnSC.png"><link rel="canonical" href="https://devsu.top/posts/e7c23ba1/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//hm.baidu.com"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><script>var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?6243425e2ecb037931274c4ca1db3132";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":true,"languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"简"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":300},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":50,"languages":{"author":"作者: Carl Su","link":"链接: ","source":"来源: 码行","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#1f1f1f","position":"bottom-left"},
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: true,
  islazyload: true,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: true,
  }
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Kotlin编程第一课--(协程篇)20  Flow：为什么说Flow是“冷”的？',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-03-27 10:56:47'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
    win.getCSS = (url,id = false) => new Promise((resolve, reject) => {
      const link = document.createElement('link')
      link.rel = 'stylesheet'
      link.href = url
      if (id) link.id = id
      link.onerror = reject
      link.onload = link.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        link.onload = link.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(link)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', 'ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          const now = new Date()
          const hour = now.getHours()
          const isNight = hour <= 6 || hour >= 18
          if (t === undefined) isNight ? activateDarkMode() : activateLightMode()
          else if (t === 'light') activateLightMode()
          else activateDarkMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.3.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><script>const preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',()=> { preloader.endLoading() })

if (false) {
  document.addEventListener('pjax:send', () => { preloader.initLoading() })
  document.addEventListener('pjax:complete', () => { preloader.endLoading() })
}</script><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="https://s2.loli.net/2023/03/09/QrI9mgJ4XlbEPzN.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">169</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">37</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">38</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 清单</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg fixed" id="page-header" style="background-image: url('https://img1.baidu.com/it/u=4050062314,1116360005&amp;fm=253&amp;fmt=auto&amp;app=138&amp;f=JPEG?w=889&amp;h=500')"><nav id="nav"><span id="blog-info"><a href="/" title="码行"><img class="site-icon" src="https://s2.loli.net/2023/03/09/whMHdYkrKoIBnSC.png"/><span class="site-name">码行</span></a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search" href="javascript:void(0);"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 清单</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Kotlin编程第一课--(协程篇)20  Flow：为什么说Flow是“冷”的？</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2022-05-30T01:51:38.000Z" title="发表于 2022-05-30 09:51:38">2022-05-30</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-03-27T02:56:47.917Z" title="更新于 2023-03-27 10:56:47">2023-03-27</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Android/">Android</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Android/Kotlin/">Kotlin</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Android/Kotlin/Kotlin%E7%BC%96%E7%A8%8B%E7%AC%AC%E4%B8%80%E8%AF%BE/">Kotlin编程第一课</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">6.4k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>23分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="Kotlin编程第一课--(协程篇)20  Flow：为什么说Flow是“冷”的？"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><p>今天我们来学习 Kotlin 协程 Flow 的基础知识。</p>
<p>Flow，可以说是在 Kotlin 协程当中自成体系的知识点。<strong>Flow 极其强大、极其灵活</strong>，在它出现之前，业界还有很多质疑 Kotlin 协程的声音，认为 Kotlin 的挂起函数、结构化并发，并不足以形成核心竞争力，在异步、并发任务的领域，RxJava 可以做得更好。</p>
<p>但是，随着 2019 年 Kotlin 推出 Flow 以后，这样的质疑声就渐渐没有了。有了 Flow 以后，Kotlin 的协程已经没有明显的短板了。简单的异步场景，我们可以直接使用挂起函数、launch、async；至于复杂的异步场景，我们就可以使用 Flow。</p>
<p>实际上，在很多技术领域，Flow 已经开始占领 RxJava 原本的领地，在 Android 领域，Flow 甚至还要取代原本 LiveData 的地位。因为，Flow 是真的香啊！</p>
<p>接下来，我们就一起来学习 Flow。</p>
<h2 id="Flow-就是“数据流”"><a href="#Flow-就是“数据流”" class="headerlink" title="Flow 就是“数据流”"></a>Flow 就是“数据流”</h2><p>Flow 这个单词有“流”的意思，比如 Cash Flow 代表了“现金流”；Traffic Flow 代表了“车流”；Flow 在 Kotlin 协程当中，其实就是“数据流”的意思。因为 Flow 当中“流淌”的，都是数据。</p>
<p>为了帮你建立思维模型，我做了一个动图，来描述 Flow 的行为模式。</p>
<p><img src= "https://s2.loli.net/2023/03/09/dog2qQY83iTIvHM.gif" data-lazy-src="https://static001.geekbang.org/resource/image/d3/81/d3138d1386ef7c863086fe9fdcbc0a81.gif?wh=1080x495" alt="img"></p>
<p>可以看到，Flow 和我们上节课学习的 Channel 不一样，Flow 并不是只有“发送”“接收”两个行为，它当中流淌的数据是<strong>可以在中途改变</strong>的。</p>
<p>Flow 的数据发送方，我们称之为“上游”；数据接收方称之为“下游”。跟现实生活中一样，上下游其实也是相对的概念。比如我们可以看到下面的图，对于中转站 2 来说，中转站 1 就相当于它的上游。</p>
<p><img src= "https://s2.loli.net/2023/03/09/dog2qQY83iTIvHM.gif" data-lazy-src="https://static001.geekbang.org/resource/image/ff/31/ffb1b4f8256ae249108d60600947c031.jpg?wh=2000x1125" alt="img"></p>
<p>另外我们也可以看到，在发送方、接收方的中间，是可以有多个“中转站”的。在这些中转站里，我们就可以对数据进行一些处理了。</p>
<p>其实，Flow 这样的数据模型，在现实生活中也存在，比如说长江，它有发源地和下游，中间还有很多大坝、水电站，甚至还有一些污水净化厂。</p>
<p>好，相信你现在对 Flow 已经有比较清晰的概念了。下面我们来看一段代码：</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段1</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="title">main</span><span class="params">()</span></span> = runBlocking &#123;</span><br><span class="line">    flow &#123;                  <span class="comment">// 上游，发源地</span></span><br><span class="line">        emit(<span class="number">1</span>)             <span class="comment">// 挂起函数</span></span><br><span class="line">        emit(<span class="number">2</span>)</span><br><span class="line">        emit(<span class="number">3</span>)</span><br><span class="line">        emit(<span class="number">4</span>)</span><br><span class="line">        emit(<span class="number">5</span>)</span><br><span class="line">    &#125;.filter &#123; it &gt; <span class="number">2</span> &#125;     <span class="comment">// 中转站1</span></span><br><span class="line">        .map &#123; it * <span class="number">2</span> &#125;     <span class="comment">// 中转站2</span></span><br><span class="line">        .take(<span class="number">2</span>)            <span class="comment">// 中转站3</span></span><br><span class="line">        .collect&#123;           <span class="comment">// 下游</span></span><br><span class="line">            println(it)</span><br><span class="line">        &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">输出结果：                       </span></span><br><span class="line"><span class="comment">6</span></span><br><span class="line"><span class="comment">8</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>如果你结合着之前的图片来分析这段代码的话，相信马上就能分析出它的执行结果。因为 Flow 的这种<strong>链式调用</strong>的 API，本身就非常符合人的阅读习惯。</p>
<p>而且，Flow 写出来的代码非常清晰易懂，我们可以对照前面的示意图来看一下：</p>
<p><img src= "https://s2.loli.net/2023/03/09/dog2qQY83iTIvHM.gif" data-lazy-src="https://static001.geekbang.org/resource/image/a0/f6/a0a912dfffebb66f428d2b8789a914f6.jpg?wh=2000x1125" alt="img"></p>
<p>说实话，Flow 这样代码模式，谁不爱呢？我们可以来简单分析一下：</p>
<ul>
<li>**flow{}**，是一个高阶函数，它的作用就是创建一个新的 Flow。在它的 Lambda 当中，我们可以使用 emit() 这个挂起函数往下游发送数据，这里的 emit 其实就是“发射”“发送”的意思。上游创建了一个“数据流”，同时也要负责发送数据。这跟现实生活也是一样的：长江里的水从上游产生，这是天经地义的。所以，对于上游而言，只需要创建 Flow，然后发送数据即可，其他的都交给中转站和下游。</li>
<li><strong>filter{}、map{}、take(2)<strong>，它们是</strong>中间操作符</strong>，就像中转站一样，它们的作用就是对数据进行处理，这很好理解。Flow 最大的优势，就是它的操作符跟集合操作符高度一致。只要你会用 List、Sequence，那你就可以快速上手 Flow 的操作符，这中间几乎没有额外的学习成本。</li>
<li>collect{}，也被称为<strong>终止操作符</strong>或者<strong>末端操作符</strong>，它的作用其实只有一个：终止 Flow 数据流，并且接收这些数据。</li>
</ul>
<p>除了使用 flow{} 创建 Flow 以外，我们还可以使用 <strong>flowOf()</strong> 这个函数。所以，从某种程度上讲，Flow 跟 Kotlin 的集合其实也是有一些相似之处的。</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段2</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="title">main</span><span class="params">()</span></span> = runBlocking &#123;</span><br><span class="line">    flowOf(<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>).filter &#123; it &gt; <span class="number">2</span> &#125;</span><br><span class="line">        .map &#123; it * <span class="number">2</span> &#125;</span><br><span class="line">        .take(<span class="number">2</span>)</span><br><span class="line">        .collect &#123;</span><br><span class="line">            println(it)</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    listOf(<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>).filter &#123; it &gt; <span class="number">2</span> &#125;</span><br><span class="line">        .map &#123; it * <span class="number">2</span> &#125;</span><br><span class="line">        .take(<span class="number">2</span>)</span><br><span class="line">        .forEach &#123;</span><br><span class="line">            println(it)</span><br><span class="line">        &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">输出结果</span></span><br><span class="line"><span class="comment">6</span></span><br><span class="line"><span class="comment">8</span></span><br><span class="line"><span class="comment">6</span></span><br><span class="line"><span class="comment">8</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>从上面的代码中，我们可以看到 Flow API 与集合 API 之间的共性。listOf 创建 List，flowOf 创建 Flow。遍历 List，我们使用 forEach{}；遍历 Flow，我们使用 collect{}。</p>
<p>在某些场景下，我们甚至可以把 Flow 当做集合来使用，或者反过来，把集合当做 Flow 来用。</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段3</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="title">main</span><span class="params">()</span></span> = runBlocking &#123;</span><br><span class="line">    <span class="comment">// Flow转List</span></span><br><span class="line">    flowOf(<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>)</span><br><span class="line">        .toList()</span><br><span class="line">        .filter &#123; it &gt; <span class="number">2</span> &#125;</span><br><span class="line">        .map &#123; it * <span class="number">2</span> &#125;</span><br><span class="line">        .take(<span class="number">2</span>)</span><br><span class="line">        .forEach &#123;</span><br><span class="line">            println(it)</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// List转Flow</span></span><br><span class="line">    listOf(<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>)</span><br><span class="line">        .asFlow()</span><br><span class="line">        .filter &#123; it &gt; <span class="number">2</span> &#125;</span><br><span class="line">        .map &#123; it * <span class="number">2</span> &#125;</span><br><span class="line">        .take(<span class="number">2</span>)</span><br><span class="line">        .collect &#123;</span><br><span class="line">            println(it)</span><br><span class="line">        &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">输出结果</span></span><br><span class="line"><span class="comment">6</span></span><br><span class="line"><span class="comment">8</span></span><br><span class="line"><span class="comment">6</span></span><br><span class="line"><span class="comment">8</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>在这段代码中，我们使用了 Flow.toList()、List.asFlow() 这两个扩展函数，让数据在 List、Flow 之间来回转换，而其中的代码甚至不需要做多少改变。</p>
<p>到这里，我其实已经给你介绍了三种创建 Flow 的方式，我来帮你总结一下。</p>
<p><img src= "https://s2.loli.net/2023/03/09/dog2qQY83iTIvHM.gif" data-lazy-src="https://static001.geekbang.org/resource/image/7a/2e/7a0a85927254e66e4847c17de49d052e.jpg?wh=2000x697" alt="img"></p>
<p>好，现在我们就对 Flow 有一个整体的认识了，我们知道它的 API 总体分为三个部分：上游、中间操作、下游。其中对于上游来说，一般有三种创建方式，这些我们也都需要好好掌握。</p>
<p>那么接下来，我们重点看看中间操作符。</p>
<h2 id="中间操作符"><a href="#中间操作符" class="headerlink" title="中间操作符"></a>中间操作符</h2><p>中间操作符（Intermediate Operators），除了之前提到的 map、filter、take 这种从集合那边“抄”来的操作符之外，还有一些特殊的操作符需要我们特别注意。这些操作符跟 Kotlin 集合 API 是没关系的，它们是<strong>专门为 Flow 设计的</strong>。我们一个个来看。</p>
<h2 id="Flow-生命周期"><a href="#Flow-生命周期" class="headerlink" title="Flow 生命周期"></a>Flow 生命周期</h2><p>在 Flow 的中间操作符当中，<strong>onStart、onCompletion</strong> 这两个是比较特殊的。它们是以操作符的形式存在，但实际上的作用，是监听生命周期回调。</p>
<p>onStart，它的作用是注册一个监听事件：当 flow 启动以后，它就会被回调。具体我们可以看下面这个例子：</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段4</span></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="title">main</span><span class="params">()</span></span> = runBlocking &#123;</span><br><span class="line">    flowOf(<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>)</span><br><span class="line">        .filter &#123;</span><br><span class="line">            println(<span class="string">&quot;filter: <span class="variable">$it</span>&quot;</span>)</span><br><span class="line">            it &gt; <span class="number">2</span></span><br><span class="line">        &#125;</span><br><span class="line">        .map &#123;</span><br><span class="line">            println(<span class="string">&quot;map: <span class="variable">$it</span>&quot;</span>)</span><br><span class="line">            it * <span class="number">2</span></span><br><span class="line">        &#125;</span><br><span class="line">        .take(<span class="number">2</span>)</span><br><span class="line">        .onStart &#123; println(<span class="string">&quot;onStart&quot;</span>) &#125; <span class="comment">// 注意这里</span></span><br><span class="line">        .collect &#123;</span><br><span class="line">            println(<span class="string">&quot;collect: <span class="variable">$it</span>&quot;</span>)</span><br><span class="line">        &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">输出结果</span></span><br><span class="line"><span class="comment">onStart</span></span><br><span class="line"><span class="comment">filter: 1</span></span><br><span class="line"><span class="comment">filter: 2</span></span><br><span class="line"><span class="comment">filter: 3</span></span><br><span class="line"><span class="comment">map: 3</span></span><br><span class="line"><span class="comment">collect: 6</span></span><br><span class="line"><span class="comment">filter: 4</span></span><br><span class="line"><span class="comment">map: 4</span></span><br><span class="line"><span class="comment">collect: 8</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>可以看到，onStart 的执行顺序，并不是严格按照上下游来执行的。虽然 onStart 的位置是处于下游，而 filter、map、take 是上游，但 onStart 是最先执行的。因为它本质上是一个回调，不是一个数据处理的中间站。</p>
<p>相应的，filter、map、take 这类操作符，它们的执行顺序是跟它们的位置相关的。最终的执行结果，也会受到位置变化的影响。</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段5</span></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="title">main</span><span class="params">()</span></span> = runBlocking &#123;</span><br><span class="line">    flowOf(<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>)</span><br><span class="line">        .take(<span class="number">2</span>) <span class="comment">// 注意这里</span></span><br><span class="line">        .filter &#123;</span><br><span class="line">            println(<span class="string">&quot;filter: <span class="variable">$it</span>&quot;</span>)</span><br><span class="line">            it &gt; <span class="number">2</span></span><br><span class="line">        &#125;</span><br><span class="line">        .map &#123;</span><br><span class="line">            println(<span class="string">&quot;map: <span class="variable">$it</span>&quot;</span>)</span><br><span class="line">            it * <span class="number">2</span></span><br><span class="line">        &#125;</span><br><span class="line">        .onStart &#123; println(<span class="string">&quot;onStart&quot;</span>) &#125;</span><br><span class="line">        .collect &#123;</span><br><span class="line">            println(<span class="string">&quot;collect: <span class="variable">$it</span>&quot;</span>)</span><br><span class="line">        &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">输出结果</span></span><br><span class="line"><span class="comment">onStart</span></span><br><span class="line"><span class="comment">filter: 1</span></span><br><span class="line"><span class="comment">filter: 2</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>可见，在以上代码中，我们将 take(2) 的位置挪到了上游的起始位置，这时候程序的执行结果就完全变了。</p>
<p>OK，理解了 onStart 以后，onCompletion 也就很好理解了。</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段6</span></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="title">main</span><span class="params">()</span></span> = runBlocking &#123;</span><br><span class="line">    flowOf(<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>)</span><br><span class="line">        .onCompletion &#123; println(<span class="string">&quot;onCompletion&quot;</span>) &#125; <span class="comment">// 注意这里</span></span><br><span class="line">        .filter &#123;</span><br><span class="line">            println(<span class="string">&quot;filter: <span class="variable">$it</span>&quot;</span>)</span><br><span class="line">            it &gt; <span class="number">2</span></span><br><span class="line">        &#125;</span><br><span class="line">        .take(<span class="number">2</span>)</span><br><span class="line">        .collect &#123;</span><br><span class="line">            println(<span class="string">&quot;collect: <span class="variable">$it</span>&quot;</span>)</span><br><span class="line">        &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">输出结果</span></span><br><span class="line"><span class="comment">filter: 1</span></span><br><span class="line"><span class="comment">filter: 2</span></span><br><span class="line"><span class="comment">filter: 3</span></span><br><span class="line"><span class="comment">collect: 3</span></span><br><span class="line"><span class="comment">filter: 4</span></span><br><span class="line"><span class="comment">collect: 4</span></span><br><span class="line"><span class="comment">onCompletion</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>和 onStart 类似，onCompletion 的执行顺序，跟它在 Flow 当中的位置无关。onCompletion 只会在 Flow 数据流执行完毕以后，才会回调。</p>
<p>还记得在第 16 讲里，我们提到的 Job.invokeOnCompletion{} 这个生命周期回调吗？在这里，Flow.onCompletion{} 也是类似的，onCompletion{} 在面对以下三种情况时都会进行回调:</p>
<ul>
<li>情况 1，Flow 正常执行完毕；</li>
<li>情况 2，Flow 当中出现异常；</li>
<li>情况 3，Flow 被取消。</li>
</ul>
<p>对于情况 1，我们已经在上面的代码中验证过了。接下来，我们看看后面两种情况：</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段7</span></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="title">main</span><span class="params">()</span></span> = runBlocking &#123;</span><br><span class="line">    launch &#123;</span><br><span class="line">        flow &#123;</span><br><span class="line">            emit(<span class="number">1</span>)</span><br><span class="line">            emit(<span class="number">2</span>)</span><br><span class="line">            emit(<span class="number">3</span>)</span><br><span class="line">        &#125;.onCompletion &#123; println(<span class="string">&quot;onCompletion first: <span class="variable">$it</span>&quot;</span>) &#125;</span><br><span class="line">            .collect &#123;</span><br><span class="line">                println(<span class="string">&quot;collect: <span class="variable">$it</span>&quot;</span>)</span><br><span class="line">                <span class="keyword">if</span> (it == <span class="number">2</span>) &#123;</span><br><span class="line">                    cancel()            <span class="comment">// 1</span></span><br><span class="line">                    println(<span class="string">&quot;cancel&quot;</span>)</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    delay(<span class="number">100L</span>)</span><br><span class="line"></span><br><span class="line">    flowOf(<span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>)</span><br><span class="line">        .onCompletion &#123; println(<span class="string">&quot;onCompletion second: <span class="variable">$it</span>&quot;</span>) &#125;</span><br><span class="line">        .collect &#123;</span><br><span class="line">            println(<span class="string">&quot;collect: <span class="variable">$it</span>&quot;</span>)</span><br><span class="line">            <span class="comment">// 仅用于测试，生产环境不应该这么创建异常</span></span><br><span class="line">            <span class="keyword">throw</span> IllegalStateException() <span class="comment">// 2</span></span><br><span class="line">        &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">collect: 1</span></span><br><span class="line"><span class="comment">collect: 2</span></span><br><span class="line"><span class="comment">cancel</span></span><br><span class="line"><span class="comment">onCompletion first: JobCancellationException: // 3</span></span><br><span class="line"><span class="comment">collect: 4</span></span><br><span class="line"><span class="comment">onCompletion second: IllegalStateException    // 4</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>在上面的注释 1 当中，我们在 collect{} 里调用了 cancel 方法，这会取消掉整个 Flow，这时候，flow{} 当中剩下的代码将不会再被执行。最后，onCompletion 也会被调用，同时，请你留意注释 3，这里还会带上对应的异常信息 JobCancellationException。</p>
<p>同样的，根据注释 2、4，我们也能分析出一样的结果。</p>
<p>而且从上面的代码里，我们也可以看到，当 Flow 当中发生异常以后，Flow 就会终止。那么对于这样的问题，我们该如何处理呢？</p>
<p>下面我就带你来看看，Flow 当中如何处理异常。</p>
<h2 id="catch-异常处理"><a href="#catch-异常处理" class="headerlink" title="catch 异常处理"></a>catch 异常处理</h2><p>前面我已经介绍过，Flow 主要有三个部分：上游、中间操作、下游。那么，Flow 当中的异常，也可以根据这个标准来进行分类，也就是异常发生的位置。</p>
<p>对于发生在上游、中间操作这两个阶段的异常，我们可以直接使用 <strong>catch</strong> 这个操作符来进行捕获和进一步处理。如下所示：</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段8</span></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="title">main</span><span class="params">()</span></span> = runBlocking &#123;</span><br><span class="line">    <span class="keyword">val</span> flow = flow &#123;</span><br><span class="line">        emit(<span class="number">1</span>)</span><br><span class="line">        emit(<span class="number">2</span>)</span><br><span class="line">        <span class="keyword">throw</span> IllegalStateException()</span><br><span class="line">        emit(<span class="number">3</span>)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    flow.map &#123; it * <span class="number">2</span> &#125;</span><br><span class="line">        .<span class="keyword">catch</span> &#123; println(<span class="string">&quot;catch: <span class="variable">$it</span>&quot;</span>) &#125; <span class="comment">// 注意这里</span></span><br><span class="line">        .collect &#123;</span><br><span class="line">            println(it)</span><br><span class="line">        &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">输出结果：</span></span><br><span class="line"><span class="comment">2</span></span><br><span class="line"><span class="comment">4</span></span><br><span class="line"><span class="comment">catch: java.lang.IllegalStateException</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>所以，catch 这个操作符，其实就相当于我们平时使用的 try-catch 的意思。只是说，后者是用于普通的代码，而前者是用于 Flow 数据流的，两者的核心理念是一样的。不过，考虑到 Flow 具有上下游的特性，catch 这个操作符的作用是<strong>和它的位置</strong>强相关的。</p>
<p><strong>catch 的作用域，仅限于 catch 的上游</strong>。换句话说，发生在 catch 上游的异常，才会被捕获，发生在 catch 下游的异常，则不会被捕获。为此，我们可以换一个写法：</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段9</span></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="title">main</span><span class="params">()</span></span> = runBlocking &#123;</span><br><span class="line">    <span class="keyword">val</span> flow = flow &#123;</span><br><span class="line">        emit(<span class="number">1</span>)</span><br><span class="line">        emit(<span class="number">2</span>)</span><br><span class="line">        emit(<span class="number">3</span>)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    flow.map &#123; it * <span class="number">2</span> &#125;</span><br><span class="line">        .<span class="keyword">catch</span> &#123; println(<span class="string">&quot;catch: <span class="variable">$it</span>&quot;</span>) &#125;</span><br><span class="line">        .filter &#123; it / <span class="number">0</span> &gt; <span class="number">1</span>&#125;  <span class="comment">// 故意制造异常</span></span><br><span class="line">        .collect &#123;</span><br><span class="line">            println(it)</span><br><span class="line">        &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">输出结果</span></span><br><span class="line"><span class="comment">Exception in thread &quot;main&quot; ArithmeticException: / by zero</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>从上面代码的执行结果里，我们可以看到，catch 对于发生在它下游的异常是无能为力的。这一点，借助我们之前的思维模型来思考，也是非常符合直觉的。比如说，长江上面的污水处理厂，当然只能处理它上游的水，而对于发生在下游的污染，是无能为力的。</p>
<p>那么，发生在上游源头，还有发生在中间操作的异常，处理起来其实很容易，我们只需要留意 catch 的作用域即可。最后就是发生在下游末尾处的异常了。</p>
<p>如果你回过头去看代码段 7 当中的异常，会发现它也是一个典型的“发生在下游的异常”，所以对于这种情况，我们就不能用 catch 操作符了。那么最简单的办法，其实是使用 <strong>try-catch</strong>，把 collect{} 当中可能出现问题的代码包裹起来。比如像下面这样：</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段10</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="title">main</span><span class="params">()</span></span> = runBlocking &#123;</span><br><span class="line">    flowOf(<span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>)</span><br><span class="line">        .onCompletion &#123; println(<span class="string">&quot;onCompletion second: <span class="variable">$it</span>&quot;</span>) &#125;</span><br><span class="line">        .collect &#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                println(<span class="string">&quot;collect: <span class="variable">$it</span>&quot;</span>)</span><br><span class="line">                <span class="keyword">throw</span> IllegalStateException()</span><br><span class="line">            &#125; <span class="keyword">catch</span> (e: Exception) &#123;</span><br><span class="line">                println(<span class="string">&quot;Catch <span class="variable">$e</span>&quot;</span>)</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>所以，针对 Flow 当中的异常处理，我们主要有两种手段：一个是 catch 操作符，它主要用于上游异常的捕获；而 try-catch 这种传统的方式，更多的是应用于下游异常的捕获。</p>
<p><code>提示：关于更多协程异常处理的话题，我们会在第 23 讲深入介绍。</code></p>
<h2 id="切换-Context：flowOn、launchIn"><a href="#切换-Context：flowOn、launchIn" class="headerlink" title="切换 Context：flowOn、launchIn"></a>切换 Context：flowOn、launchIn</h2><p>前面我们介绍过，Flow 非常适合复杂的异步任务。在大部分的异步任务当中，我们都需要频繁切换工作的线程。对于耗时任务，我们需要线程池当中执行，对于 UI 任务，我们需要在主线程执行。</p>
<p>而在 Flow 当中，我们借助 <strong>flowOn</strong> 这一个操作符，就可以灵活实现以上的需求。</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段11</span></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="title">main</span><span class="params">()</span></span> = runBlocking &#123;</span><br><span class="line">    <span class="keyword">val</span> flow = flow &#123;</span><br><span class="line">        logX(<span class="string">&quot;Start&quot;</span>)</span><br><span class="line">        emit(<span class="number">1</span>)</span><br><span class="line">        logX(<span class="string">&quot;Emit: 1&quot;</span>)</span><br><span class="line">        emit(<span class="number">2</span>)</span><br><span class="line">        logX(<span class="string">&quot;Emit: 2&quot;</span>)</span><br><span class="line">        emit(<span class="number">3</span>)</span><br><span class="line">        logX(<span class="string">&quot;Emit: 3&quot;</span>)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    flow.filter &#123;</span><br><span class="line">            logX(<span class="string">&quot;Filter: <span class="variable">$it</span>&quot;</span>)</span><br><span class="line">            it &gt; <span class="number">2</span></span><br><span class="line">        &#125;</span><br><span class="line">        .flowOn(Dispatchers.IO)  <span class="comment">// 注意这里</span></span><br><span class="line">        .collect &#123;</span><br><span class="line">            logX(<span class="string">&quot;Collect <span class="variable">$it</span>&quot;</span>)</span><br><span class="line">        &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">输出结果</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">Start</span></span><br><span class="line"><span class="comment">Thread:DefaultDispatcher-worker-1 @coroutine#2</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">Filter: 1</span></span><br><span class="line"><span class="comment">Thread:DefaultDispatcher-worker-1 @coroutine#2</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">Emit: 1</span></span><br><span class="line"><span class="comment">Thread:DefaultDispatcher-worker-1 @coroutine#2</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">Filter: 2</span></span><br><span class="line"><span class="comment">Thread:DefaultDispatcher-worker-1 @coroutine#2</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">Emit: 2</span></span><br><span class="line"><span class="comment">Thread:DefaultDispatcher-worker-1 @coroutine#2</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">Filter: 3</span></span><br><span class="line"><span class="comment">Thread:DefaultDispatcher-worker-1 @coroutine#2</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">Emit: 3</span></span><br><span class="line"><span class="comment">Thread:DefaultDispatcher-worker-1 @coroutine#2</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">Collect 3</span></span><br><span class="line"><span class="comment">Thread:main @coroutine#1</span></span><br><span class="line"><span class="comment">================================</span></span><br></pre></td></tr></table></figure>

<p>flowOn 操作符也是和它的位置强相关的。它的作用域跟前面的 catch 类似：<strong>flowOn 仅限于它的上游</strong>。</p>
<p>在上面的代码中，flowOn 的上游，就是 flow{}、filter{} 当中的代码，所以，它们的代码全都运行在 DefaultDispatcher 这个线程池当中。只有 collect{} 当中的代码是运行在 main 线程当中的。</p>
<p>对应的，如果你挪动一下上面代码中 flowOn 的位置，会发现执行结果就会不一样，比如这样：</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段12</span></span><br><span class="line">flow.flowOn(Dispatchers.IO) <span class="comment">// 注意这里</span></span><br><span class="line">    .filter &#123;</span><br><span class="line">        logX(<span class="string">&quot;Filter: <span class="variable">$it</span>&quot;</span>)</span><br><span class="line">        it &gt; <span class="number">2</span></span><br><span class="line">    &#125;</span><br><span class="line">    .collect &#123;</span><br><span class="line">        logX(<span class="string">&quot;Collect <span class="variable">$it</span>&quot;</span>)</span><br><span class="line">    &#125;</span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">输出结果：</span></span><br><span class="line"><span class="comment">filter当中的代码会执行在main线程</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>这里的代码执行结果，我们很容易就能推测出来，因为 flowOn 的作用域仅限于上游，所以它只会让 flow{} 当中的代码运行在 DefaultDispatcher 当中，剩下的代码则执行在 main 线程。</p>
<p>但是到这里，我们就会遇到一个类似 catch 的困境：如果想要指定 collect 当中的 Context，该怎么办呢？</p>
<p>我们能想到的最简单的办法，就是用前面学过的：**withContext{}**。</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段13</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 不推荐</span></span><br><span class="line">flow.flowOn(Dispatchers.IO)</span><br><span class="line">    .filter &#123;</span><br><span class="line">        logX(<span class="string">&quot;Filter: <span class="variable">$it</span>&quot;</span>)</span><br><span class="line">        it &gt; <span class="number">2</span></span><br><span class="line">    &#125;</span><br><span class="line">    .collect &#123;</span><br><span class="line">        withContext(mySingleDispatcher) &#123;</span><br><span class="line">            logX(<span class="string">&quot;Collect <span class="variable">$it</span>&quot;</span>)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">输出结果：</span></span><br><span class="line"><span class="comment">collect&#123;&#125;将运行在MySingleThread</span></span><br><span class="line"><span class="comment">filter&#123;&#125;运行在main</span></span><br><span class="line"><span class="comment">flow&#123;&#125;运行在DefaultDispatcher</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>



<p>在上面的代码中，我们直接在 collect{} 里使用了 withContext{}，所以它的执行就交给了 MySingleThread。不过，有的时候，我们想要改变除了 flowOn 以外所有代码的 Context。比如，我们希望 collect{}、filter{} 都运行在 MySingleThread。</p>
<p>那么这时候，我们可以考虑使用 withContext{} 进一步<strong>扩大包裹的范围</strong>，就像下面这样：</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段14</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 不推荐</span></span><br><span class="line">withContext(mySingleDispatcher) &#123;</span><br><span class="line">    flow.flowOn(Dispatchers.IO)</span><br><span class="line">        .filter &#123;</span><br><span class="line">            logX(<span class="string">&quot;Filter: <span class="variable">$it</span>&quot;</span>)</span><br><span class="line">            it &gt; <span class="number">2</span></span><br><span class="line">        &#125;</span><br><span class="line">        .collect&#123;</span><br><span class="line">            logX(<span class="string">&quot;Collect <span class="variable">$it</span>&quot;</span>)</span><br><span class="line">        &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">输出结果：</span></span><br><span class="line"><span class="comment">collect&#123;&#125;将运行在MySingleThread</span></span><br><span class="line"><span class="comment">filter&#123;&#125;运行在MySingleThread</span></span><br><span class="line"><span class="comment">flow&#123;&#125;运行在DefaultDispatcher</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>不过，这种写法终归是有些丑陋，因此，Kotlin 官方还为我们提供了另一个操作符，<strong>launchIn</strong>。</p>
<p>我们来看看这个操作符是怎么用的：</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段15</span></span><br><span class="line"><span class="keyword">val</span> scope = CoroutineScope(mySingleDispatcher)</span><br><span class="line">flow.flowOn(Dispatchers.IO)</span><br><span class="line">    .filter &#123;</span><br><span class="line">        logX(<span class="string">&quot;Filter: <span class="variable">$it</span>&quot;</span>)</span><br><span class="line">        it &gt; <span class="number">2</span></span><br><span class="line">    &#125;</span><br><span class="line">    .onEach &#123;</span><br><span class="line">        logX(<span class="string">&quot;onEach <span class="variable">$it</span>&quot;</span>)</span><br><span class="line">    &#125;</span><br><span class="line">    .launchIn(scope)</span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">输出结果：</span></span><br><span class="line"><span class="comment">onEach&#123;&#125;将运行在MySingleThread</span></span><br><span class="line"><span class="comment">filter&#123;&#125;运行在MySingleThread</span></span><br><span class="line"><span class="comment">flow&#123;&#125;运行在DefaultDispatcher</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>可以看到，在这段代码中，我们不再直接使用 collect{}，而是借助了 onEach{} 来实现类似 collect{} 的功能。同时我们在最后使用了 launchIn(scope)，把它上游的代码都分发到指定的线程当中。</p>
<p>如果你去看 launchIn 的源代码的话，你会发现它的定义极其简单：</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段16</span></span><br><span class="line"><span class="keyword">public</span> <span class="function"><span class="keyword">fun</span> <span class="type">&lt;T&gt;</span> Flow<span class="type">&lt;T&gt;</span>.<span class="title">launchIn</span><span class="params">(scope: <span class="type">CoroutineScope</span>)</span></span>: Job = scope.launch &#123;</span><br><span class="line">    collect() <span class="comment">// tail-call</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>由此可见，launchIn 从严格意义来讲，应该算是一个下游的终止操作符，因为它本质上是调用了 collect()。</p>
<p>因此，上面的代码段 16，也会等价于下面的写法：</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段17</span></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="title">main</span><span class="params">()</span></span> = runBlocking &#123;</span><br><span class="line">    <span class="keyword">val</span> scope = CoroutineScope(mySingleDispatcher)</span><br><span class="line">    <span class="keyword">val</span> flow = flow &#123;</span><br><span class="line">        logX(<span class="string">&quot;Start&quot;</span>)</span><br><span class="line">        emit(<span class="number">1</span>)</span><br><span class="line">        logX(<span class="string">&quot;Emit: 1&quot;</span>)</span><br><span class="line">        emit(<span class="number">2</span>)</span><br><span class="line">        logX(<span class="string">&quot;Emit: 2&quot;</span>)</span><br><span class="line">        emit(<span class="number">3</span>)</span><br><span class="line">        logX(<span class="string">&quot;Emit: 3&quot;</span>)</span><br><span class="line">    &#125;</span><br><span class="line">        .flowOn(Dispatchers.IO)</span><br><span class="line">        .filter &#123;</span><br><span class="line">            logX(<span class="string">&quot;Filter: <span class="variable">$it</span>&quot;</span>)</span><br><span class="line">            it &gt; <span class="number">2</span></span><br><span class="line">        &#125;</span><br><span class="line">        .onEach &#123;</span><br><span class="line">            logX(<span class="string">&quot;onEach <span class="variable">$it</span>&quot;</span>)</span><br><span class="line">        &#125;</span><br><span class="line">        </span><br><span class="line">    scope.launch &#123; <span class="comment">// 注意这里</span></span><br><span class="line">        flow.collect()</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    delay(<span class="number">100L</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>所以，总的来说，对于 Flow 当中的线程切换，我们可以使用 flowOn、launchIn、withContext，但其实，flowOn、launchIn 就已经可以满足需求了。</p>
<p>另外，由于 Flow 当中直接使用 withContext 是很容易引发其他问题的，因此，<strong>withContext 在 Flow 当中是不被推荐的，即使要用，也应该谨慎再谨慎</strong>。</p>
<p><code>提示：针对 Flow 当中 withContext 引发的问题，我会在这节课的思考题里给出具体案例。</code></p>
<h2 id="下游：终止操作符"><a href="#下游：终止操作符" class="headerlink" title="下游：终止操作符"></a>下游：终止操作符</h2><p>最后，我们就到了下游阶段，我们来看看终止操作符（Terminal Operators）的含义和使用.</p>
<p><code>这里的 Terminal，其实有终止、末尾、终点的意思。</code></p>
<p>在 Flow 当中，终止操作符的意思就是终止整个 Flow 流程的操作符。这里的“终止”，其实是跟前面的“中间”操作符对应的。</p>
<p>具体来说，就是在 filter 操作符的后面，还可以继续添加其他的操作符，比如说 map，因为 filter 本身就是一个“中间”操作符。但是，collect 操作符之后，我们无法继续使用 map 之类的操作，因为 collect 是一个“终止”操作符，代表 Flow 数据流的终止。</p>
<p>Flow 里面，最常见的终止操作符就是 collect。除此之外，还有一些从集合当中“抄”过来的操作符，也是 Flow 的终止操作符。比如 first()、single()、fold{}、reduce{}。</p>
<p>另外，当我们尝试将 Flow 转换成集合的时候，它本身也就意味着 Flow 数据流的终止。比如说，我们前面用过的 toList：</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段18</span></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="title">main</span><span class="params">()</span></span> = runBlocking &#123;</span><br><span class="line">    <span class="comment">// Flow转List</span></span><br><span class="line">    flowOf(<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>)</span><br><span class="line">        .toList()           <span class="comment">// 注意这里</span></span><br><span class="line">        .filter &#123; it &gt; <span class="number">2</span> &#125;</span><br><span class="line">        .map &#123; it * <span class="number">2</span> &#125;</span><br><span class="line">        .take(<span class="number">2</span>)</span><br><span class="line">        .forEach &#123;</span><br><span class="line">            println(it)</span><br><span class="line">        &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在上面的代码中，当我们调用了 toList() 以后，往后所有的操作符，都不再是 Flow 的 API 调用了，虽然它们的名字没有变，filter、map，这些都只是集合的 API。所以，严格意义上讲，toList 也算是一个终止操作符。</p>
<h2 id="为什么说-Flow-是“冷”的？"><a href="#为什么说-Flow-是“冷”的？" class="headerlink" title="为什么说 Flow 是“冷”的？"></a>为什么说 Flow 是“冷”的？</h2><p>现在我们就算是把 Flow 这个 API 给搞清楚了，但还有一个疑问我们没解决，就是这节课的标题：为什么说 Flow 是“冷”的？</p>
<p>实际上，如果你理解了上节课 Channel 为什么是“热”的，那你就一定可以理解 Flow 为什么是“冷”的。我们可以模仿上节课的 Channel 代码，写一段 Flow 的代码，两相对比之下其实马上就能发现它们之间的差异了。</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段19</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="title">main</span><span class="params">()</span></span> = runBlocking &#123;</span><br><span class="line">    <span class="comment">// 冷数据流</span></span><br><span class="line">    <span class="keyword">val</span> flow = flow &#123;</span><br><span class="line">        (<span class="number">1.</span><span class="number">.3</span>).forEach &#123;</span><br><span class="line">            println(<span class="string">&quot;Before send <span class="variable">$it</span>&quot;</span>)</span><br><span class="line">            emit(it)</span><br><span class="line">            println(<span class="string">&quot;Send <span class="variable">$it</span>&quot;</span>)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 热数据流</span></span><br><span class="line">    <span class="keyword">val</span> channel = produce&lt;<span class="built_in">Int</span>&gt;(capacity = <span class="number">0</span>) &#123;</span><br><span class="line">        (<span class="number">1.</span><span class="number">.3</span>).forEach &#123;</span><br><span class="line">            println(<span class="string">&quot;Before send <span class="variable">$it</span>&quot;</span>)</span><br><span class="line">            send(it)</span><br><span class="line">            println(<span class="string">&quot;Send <span class="variable">$it</span>&quot;</span>)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    println(<span class="string">&quot;end&quot;</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">输出结果：</span></span><br><span class="line"><span class="comment">end</span></span><br><span class="line"><span class="comment">Before send 1</span></span><br><span class="line"><span class="comment">// Flow 当中的代码并未执行</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>我们知道，Channel 之所以被认为是“热”的原因，是因为<strong>不管有没有接收方，发送方都会工作</strong>。那么对应的，Flow 被认为是“冷”的原因，就是因为<strong>只有调用终止操作符之后，Flow 才会开始工作</strong>。</p>
<p><em><strong>Flow 还是“懒”的</strong></em></p>
<p>其实，如果你去仔细调试过代码段 1 的话，应该就已经发现了，Flow 不仅是“冷”的，它还是“懒”的。为了暴露出它的这个特点，我们稍微改造一下代码段 1，然后加一些日志进来。</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段20</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="title">main</span><span class="params">()</span></span> = runBlocking &#123;</span><br><span class="line">    flow &#123;</span><br><span class="line">        println(<span class="string">&quot;emit: 3&quot;</span>)</span><br><span class="line">        emit(<span class="number">3</span>)</span><br><span class="line">        println(<span class="string">&quot;emit: 4&quot;</span>)</span><br><span class="line">        emit(<span class="number">4</span>)</span><br><span class="line">        println(<span class="string">&quot;emit: 5&quot;</span>)</span><br><span class="line">        emit(<span class="number">5</span>)</span><br><span class="line">    &#125;.filter &#123;</span><br><span class="line">        println(<span class="string">&quot;filter: <span class="variable">$it</span>&quot;</span>)</span><br><span class="line">        it &gt; <span class="number">2</span></span><br><span class="line">    &#125;.map &#123;</span><br><span class="line">        println(<span class="string">&quot;map: <span class="variable">$it</span>&quot;</span>)</span><br><span class="line">        it * <span class="number">2</span></span><br><span class="line">    &#125;.collect &#123;</span><br><span class="line">        println(<span class="string">&quot;collect: <span class="variable">$it</span>&quot;</span>)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">输出结果：</span></span><br><span class="line"><span class="comment">emit: 3</span></span><br><span class="line"><span class="comment">filter: 3</span></span><br><span class="line"><span class="comment">map: 3</span></span><br><span class="line"><span class="comment">collect: 6</span></span><br><span class="line"><span class="comment">emit: 4</span></span><br><span class="line"><span class="comment">filter: 4</span></span><br><span class="line"><span class="comment">map: 4</span></span><br><span class="line"><span class="comment">collect: 8</span></span><br><span class="line"><span class="comment">emit: 5</span></span><br><span class="line"><span class="comment">filter: 5</span></span><br><span class="line"><span class="comment">map: 5</span></span><br><span class="line"><span class="comment">collect: 10</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>通过上面的运行结果，我们可以发现，Flow 一次只会处理一条数据。虽然它也是 Flow“冷”的一种表现，但这个特性准确来说是“懒”。</p>
<p>如果你结合上节课“服务员端茶送水”的场景来思考的话，Flow 不仅是一个“冷淡”的服务员，还是一个“懒惰”的服务员：明明饭桌上有 3 个人需要喝水，但服务员偏偏不一次性上 3 杯水，而是要这 3 个人，每个人都叫服务员一次，服务员才会一杯一杯地送 3 杯水过来。</p>
<p>对比 Channel 的思维模型来看的话：</p>
<p><img src= "https://s2.loli.net/2023/03/09/dog2qQY83iTIvHM.gif" data-lazy-src="https://static001.geekbang.org/resource/image/4a/59/4aaae2c6b5e14c7ae938b630d2794e59.jpg?wh=2000x762" alt="img"></p>
<p><code>提示：Flow 默认情况下是“懒惰”的，但也可以通过配置让它“勤快”起来。</code></p>
<h2 id="思考与实战"><a href="#思考与实战" class="headerlink" title="思考与实战"></a>思考与实战</h2><p>我们都知道，Flow 非常适合复杂的异步任务场景。借助它的 flowOn、launchIn，我们可以写出非常灵活的代码。比如说，在 Android、Swing 之类的 UI 平台之上，我们可以这样写：</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段21</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="title">main</span><span class="params">()</span></span> = runBlocking &#123;</span><br><span class="line">    <span class="function"><span class="keyword">fun</span> <span class="title">loadData</span><span class="params">()</span></span> = flow &#123;</span><br><span class="line">        repeat(<span class="number">3</span>)&#123;</span><br><span class="line">            delay(<span class="number">100L</span>)</span><br><span class="line">            emit(it)</span><br><span class="line">            logX(<span class="string">&quot;emit <span class="variable">$it</span>&quot;</span>)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 模拟Android、Swing的UI</span></span><br><span class="line">    <span class="keyword">val</span> uiScope = CoroutineScope(mySingleDispatcher)</span><br><span class="line"></span><br><span class="line">    loadData()</span><br><span class="line">        .map &#123; it * <span class="number">2</span> &#125;</span><br><span class="line">        .flowOn(Dispatchers.IO) <span class="comment">// 1，耗时任务</span></span><br><span class="line">        .onEach &#123;</span><br><span class="line">            logX(<span class="string">&quot;onEach <span class="variable">$it</span>&quot;</span>)</span><br><span class="line">        &#125;</span><br><span class="line">        .launchIn(uiScope)      <span class="comment">// 2，UI任务</span></span><br><span class="line"></span><br><span class="line">    delay(<span class="number">1000L</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这段代码很容易理解，我们让耗时任务在 IO 线程池执行，更新 UI 则在 UI 线程。</p>
<p>如果结合我们前面学过的 Flow 操作符，我们还可以设计出更加有意思的代码：</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段22</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="title">main</span><span class="params">()</span></span> = runBlocking &#123;</span><br><span class="line">    <span class="function"><span class="keyword">fun</span> <span class="title">loadData</span><span class="params">()</span></span> = flow &#123;</span><br><span class="line">        repeat(<span class="number">3</span>) &#123;</span><br><span class="line">            delay(<span class="number">100L</span>)</span><br><span class="line">            emit(it)</span><br><span class="line">            logX(<span class="string">&quot;emit <span class="variable">$it</span>&quot;</span>)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">fun</span> <span class="title">updateUI</span><span class="params">(it: <span class="type">Int</span>)</span></span> &#123;&#125;</span><br><span class="line">    <span class="function"><span class="keyword">fun</span> <span class="title">showLoading</span><span class="params">()</span></span> &#123; println(<span class="string">&quot;Show loading&quot;</span>) &#125;</span><br><span class="line">    <span class="function"><span class="keyword">fun</span> <span class="title">hideLoading</span><span class="params">()</span></span> &#123; println(<span class="string">&quot;Hide loading&quot;</span>) &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">val</span> uiScope = CoroutineScope(mySingleDispatcher)</span><br><span class="line"></span><br><span class="line">    loadData()</span><br><span class="line">        .onStart &#123; showLoading() &#125;          <span class="comment">// 显示加载弹窗</span></span><br><span class="line">        .map &#123; it * <span class="number">2</span> &#125;</span><br><span class="line">        .flowOn(Dispatchers.IO)</span><br><span class="line">        .<span class="keyword">catch</span> &#123; throwable -&gt;</span><br><span class="line">            println(throwable)</span><br><span class="line">            hideLoading()                   <span class="comment">// 隐藏加载弹窗</span></span><br><span class="line">            emit(-<span class="number">1</span>)                   <span class="comment">// 发生异常以后，指定默认值</span></span><br><span class="line">        &#125;</span><br><span class="line">        .onEach &#123; updateUI(it) &#125;            <span class="comment">// 更新UI界面 </span></span><br><span class="line">        .onCompletion &#123; hideLoading() &#125;     <span class="comment">// 隐藏加载弹窗</span></span><br><span class="line">        .launchIn(uiScope)</span><br><span class="line"></span><br><span class="line">    delay(<span class="number">10000L</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在以上代码中，我们通过监听 onStart、onCompletion 的回调事件，就可以实现 Loading 弹窗的显示和隐藏。而对于出现异常的情况，我们也可以在 catch{} 当中调用 emit()，给出一个默认值，这样就可以有效防止 UI 界面出现空白。</p>
<p>不得不说，以上代码的可读性是非常好的。</p>
<h2 id="小结"><a href="#小结" class="headerlink" title="小结"></a>小结</h2><p>这节课的内容到这里就差不多结束了，我们来做一个简单的总结。</p>
<ul>
<li>Flow，就是<strong>数据流</strong>。整个 Flow 的 API 设计，可以大致分为三个部分，上游的源头、中间操作符、下游终止操作符。</li>
<li>对于<strong>上游源头</strong>来说，它主要负责：创建 Flow，并且产生数据。而创建 Flow，主要有三种方式：flow{}、flowOf()、asFlow()。</li>
<li>对于<strong>中间操作符</strong>来说，它也分为几大类。第一类是从集合“抄”过来的操作符，比如 map、filter；第二类是生命周期回调，比如 onStart、onCompletion；第三类是功能型 API，比如说 flowOn 切换 Context、catch 捕获上游的异常。</li>
<li>对于<strong>下游的终止操作符</strong>，也是分为三大类。首先，就是 collect 这个最基础的终止操作符；其次，就是从集合 API“抄”过来的操作符，比如 fold、reduce；最后，就是 Flow 转换成集合的 API，比如说 flow.toList()。</li>
</ul>
<p>你也要清楚为什么我们说“Flow 是冷的”的原因，以及它对比 Channel 的优势和劣势。另外在课程里，我们还探索了 Flow 在 Android 里的实际应用场景，当我们将 Flow 与它的操作符灵活组合到一起的时候，就可以设计出可读性非常好的代码。</p>
<p><img src= "https://s2.loli.net/2023/03/09/dog2qQY83iTIvHM.gif" data-lazy-src="https://static001.geekbang.org/resource/image/74/1a/747837c1b0657ae4042fbce9eae75f1a.jpg?wh=2000x1306" alt="img"></p>
<p>其实，Flow 本身就是一个非常大的话题，能讲的知识点实在太多了。但考虑到咱们课程学习需要循序渐进，现阶段我只是从中挑选一些最重要、最关键的知识点来讲。更多 Flow 的高阶用法，等我们学完协程篇、源码篇之后，我会再考虑增加一些更高阶的内容进来。</p>
<h2 id="思考题"><a href="#思考题" class="headerlink" title="思考题"></a>思考题</h2><p>前面我曾提到过，Flow 当中直接使用 withContext{}，是很容易出现问题的，下面代码是其中的一种。请问你能解释其中的缘由吗？Kotlin 官方为什么要这么设计？</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段23</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="title">main</span><span class="params">()</span></span> = runBlocking &#123;</span><br><span class="line">    flow &#123;</span><br><span class="line">        withContext(Dispatchers.IO) &#123;</span><br><span class="line">            emit(<span class="number">1</span>)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;.map &#123; it * <span class="number">2</span> &#125;</span><br><span class="line">        .collect()</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">输出结果</span></span><br><span class="line"><span class="comment">IllegalStateException: Flow invariant is violated</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>这个问题的答案，我会在第 32 讲介绍 Flow 源码的时候给出详细的解释。</p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://devsu.top">Carl Su</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://devsu.top/posts/e7c23ba1/">https://devsu.top/posts/e7c23ba1/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://devsu.top" target="_blank">码行</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Kotlin/">Kotlin</a></div><div class="post_share"><div class="social-share" data-image="https://img1.baidu.com/it/u=4050062314,1116360005&amp;fm=253&amp;fmt=auto&amp;app=138&amp;f=JPEG?w=889&amp;h=500" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/posts/4b3d9f4d/" title="Kotlin编程第一课--(协程篇)21  select：到底是在选择什么？"><img class="cover" src="https://pic.rmb.bdstatic.com/66c29f8df73f201a1b3f3f1661ccf957.jpeg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Kotlin编程第一课--(协程篇)21  select：到底是在选择什么？</div></div></a></div><div class="next-post pull-right"><a href="/posts/8f28ab97/" title="kotlin编程第一课--(协程篇)19  channel：为什么说channel是热的?"><img class="cover" src="https://s2.loli.net/2023/03/14/brkf1VM6WF4UZD9.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">kotlin编程第一课--(协程篇)19  channel：为什么说channel是热的?</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/posts/85d82fa8/" title="Kotlin编程第一课--(基础篇)06  扩展：你的能力边界到底在哪里？"><img class="cover" src="https://static001.geekbang.org/resource/image/b6/1c/b65feyy0bdc4764c6564a95912d7851c.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-05-06</div><div class="title">Kotlin编程第一课--(基础篇)06  扩展：你的能力边界到底在哪里？</div></div></a></div><div><a href="/posts/be9f17d6/" title="Kotlin编程第一课(目录)"><img class="cover" src="https://img2.baidu.com/it/u=3956021957,3313212296&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=500" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-07-10</div><div class="title">Kotlin编程第一课(目录)</div></div></a></div><div><a href="/posts/83a7144c/" title="2023-01-17-Kotlin协程 -  结构化并发"><img class="cover" src="https://s2.loli.net/2023/03/14/xEyFgn24zZPXe15.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-01-17</div><div class="title">2023-01-17-Kotlin协程 -  结构化并发</div></div></a></div><div><a href="/posts/68bf7d20/" title="Kotlin函数"><img class="cover" src="https://img1.baidu.com/it/u=1546227440,2897989905&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-08-05</div><div class="title">Kotlin函数</div></div></a></div><div><a href="/posts/a20c9e06/" title="Kotlin协程"><img class="cover" src="https://s2.loli.net/2023/03/14/3MHPBy1Q4GncRlF.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-02-09</div><div class="title">Kotlin协程</div></div></a></div><div><a href="/posts/8c331668/" title="Kotlin内置函数apply、let、run、with、also等区别"><img class="cover" src="https://s2.loli.net/2023/03/14/OpxWcuy2ktMzoQD.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-08-05</div><div class="title">Kotlin内置函数apply、let、run、with、also等区别</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div><div id="comment-switch"><span class="first-comment">Valine</span><span class="switch-btn"></span><span class="second-comment">Disqus</span></div></div><div class="comment-wrap"><div><div class="vcomment" id="vcomment"></div></div><div><div id="disqus_thread"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#Flow-%E5%B0%B1%E6%98%AF%E2%80%9C%E6%95%B0%E6%8D%AE%E6%B5%81%E2%80%9D"><span class="toc-number">1.</span> <span class="toc-text">Flow 就是“数据流”</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B8%AD%E9%97%B4%E6%93%8D%E4%BD%9C%E7%AC%A6"><span class="toc-number">2.</span> <span class="toc-text">中间操作符</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Flow-%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F"><span class="toc-number">3.</span> <span class="toc-text">Flow 生命周期</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#catch-%E5%BC%82%E5%B8%B8%E5%A4%84%E7%90%86"><span class="toc-number">4.</span> <span class="toc-text">catch 异常处理</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%88%87%E6%8D%A2-Context%EF%BC%9AflowOn%E3%80%81launchIn"><span class="toc-number">5.</span> <span class="toc-text">切换 Context：flowOn、launchIn</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B8%8B%E6%B8%B8%EF%BC%9A%E7%BB%88%E6%AD%A2%E6%93%8D%E4%BD%9C%E7%AC%A6"><span class="toc-number">6.</span> <span class="toc-text">下游：终止操作符</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B8%BA%E4%BB%80%E4%B9%88%E8%AF%B4-Flow-%E6%98%AF%E2%80%9C%E5%86%B7%E2%80%9D%E7%9A%84%EF%BC%9F"><span class="toc-number">7.</span> <span class="toc-text">为什么说 Flow 是“冷”的？</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%80%9D%E8%80%83%E4%B8%8E%E5%AE%9E%E6%88%98"><span class="toc-number">8.</span> <span class="toc-text">思考与实战</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%B0%8F%E7%BB%93"><span class="toc-number">9.</span> <span class="toc-text">小结</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%80%9D%E8%80%83%E9%A2%98"><span class="toc-number">10.</span> <span class="toc-text">思考题</span></a></li></ol></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2018 - 2023 By Carl Su</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text">学无止境</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="chat_btn" type="button" title="聊天"><i class="fas fa-sms"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><div class="js-pjax"><script>function loadValine () {
  function initValine () {
    const valine = new Valine(Object.assign({
      el: '#vcomment',
      appId: '',
      appKey: '',
      avatar: 'monsterid',
      serverURLs: '',
      emojiMaps: "",
      path: window.location.pathname,
      visitor: false
    }, null))
  }

  if (typeof Valine === 'function') initValine() 
  else getScript('https://cdn.jsdelivr.net/npm/valine/dist/Valine.min.js').then(initValine)
}

if ('Valine' === 'Valine' || !true) {
  if (true) btf.loadComment(document.getElementById('vcomment'),loadValine)
  else setTimeout(loadValine, 0)
} else {
  function loadOtherComment () {
    loadValine()
  }
}</script><script>function loadDisqus () {
  var disqus_config = function () {
    this.page.url = 'https://devsu.top/posts/e7c23ba1/'
    this.page.identifier = '/posts/e7c23ba1/'
    this.page.title = 'Kotlin编程第一课--(协程篇)20  Flow：为什么说Flow是“冷”的？'
  };

  window.disqusReset = () => {
    DISQUS.reset({
      reload: true,
      config: disqus_config
    })
  }

  if (window.DISQUS) disqusReset()
  else {
    (function() { 
      var d = document, s = d.createElement('script');
      s.src = 'https://.disqus.com/embed.js';
      s.setAttribute('data-timestamp', +new Date());
      (d.head || d.body).appendChild(s);
    })();
  }

  document.getElementById('darkmode').addEventListener('click', () => {
    setTimeout(() => window.disqusReset(), 200)
  })
}

if ('Valine' === 'Disqus' || !true) {
  if (true) btf.loadComment(document.getElementById('disqus_thread'), loadDisqus)
  else loadDisqus()
} else {
  function loadOtherComment () {
    loadDisqus()
  }
}
</script></div><script defer="defer" id="fluttering_ribbon" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/canvas-fluttering-ribbon.min.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = false;
POWERMODE.mobile = false;
document.body.addEventListener('input', POWERMODE);
</script><script id="click-heart" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/click-heart.min.js" async="async" mobile="false"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div><script src="/js/search/local-search.js"></script></div></body></html>